        //
//  PhotoBrowserCell.swift
//  weibo
//
//  Created by 吴婷婷 on 15/11/18.
//  Copyright © 2015年 wutingting. All rights reserved.
//

import UIKit
import SDWebImage
import SVProgressHUD
//点击图片协议
protocol PhotoBrowserCellDelegate: NSObjectProtocol {
    func PhotoBrowserCellDidClickImage()
}
        
class PhotoBrowserCell: UICollectionViewCell {
    //MARK: - 监听方法
    @objc private func tapImage() {
        photoDelegate?.PhotoBrowserCellDidClickImage()
    }
    //代理
    var photoDelegate: PhotoBrowserCellDelegate?
    //MARK: - 设置图片
    var imageURL: NSURL? {
        didSet {

            guard let url = imageURL else {
                return
            }
            //重置scrollView
            resetScrollView()
            
            let key = url.absoluteString
            let placeHolderImage = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            setPlaceHolder(placeHolderImage)
            
            
            imageView.sd_setImageWithURL(middleUrl(url), placeholderImage: nil, options: [SDWebImageOptions.RetryFailed,SDWebImageOptions.RefreshCached], progress: { (current, total) -> Void in
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    let progress = CGFloat(current) / CGFloat(total)
                    self.placeHolderImageView.progress = progress
                })
                }) { (image, error, _, _) -> Void in
                    
                    self.placeHolderImageView.hidden = true
                    
                    self.setImagePosition(image)
            }
        }
    }
    ///设置占位图片
    private func setPlaceHolder(image: UIImage?) {
        placeHolderImageView.hidden = false

        placeHolderImageView.image = image
        placeHolderImageView.sizeToFit()
        placeHolderImageView.center = scrollView.center
    }
    
    ///复原scrollView
    private func resetScrollView() {
        imageView.transform = CGAffineTransformIdentity
        
        scrollView.contentInset = UIEdgeInsetsZero
        scrollView.contentSize = CGSizeZero
        scrollView.contentOffset = CGPointZero
    }
    ///计算图片位置
    private func setImagePosition(image: UIImage) {
        let size = displaySize(image)
        
        
        if size.height > scrollView.bounds.height {
            imageView.frame = CGRect(origin: CGPointZero, size: size)
            scrollView.contentSize = size
        } else {
            let y = (scrollView.bounds.height - size.height) * 0.5
            imageView.frame = CGRect(origin: CGPointZero, size: size)
            scrollView.contentInset = UIEdgeInsetsMake(y, 0, 0, 0)
        }
        
    }
    ///计算显示图像的大小
    private func displaySize(image: UIImage) -> CGSize {
        let w = scrollView.bounds.width
        let h = image.size.height * w / image.size.width
        
        return CGSizeMake(w, h)
        
    }
    ///缩略图转换成中等图片
    private func middleUrl(url: NSURL)->NSURL {
        var urlString = url.absoluteString
        urlString = urlString.stringByReplacingOccurrencesOfString("/thumbnail/", withString: "/bmiddle/")
        
        return NSURL(string: urlString)!
    }
    //MARK: - 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - 设置界面
    private func setupUI() {
        //添加控件
        contentView.addSubview(scrollView)
        scrollView.addSubview(imageView)
        scrollView.addSubview(placeHolderImageView)
        
        //设置大小
        var rect = bounds
        rect.size.width -= 20
        scrollView.frame = rect
        
        //设置代理和缩放比例
        scrollView.delegate = self
        scrollView.minimumZoomScale = 0.5
        scrollView.maximumZoomScale = 2
        
        //添加手势识别
        let tap = UITapGestureRecognizer(target: self, action: "tapImage")
        imageView.userInteractionEnabled = true
        imageView.addGestureRecognizer(tap)
    }
    
    //MARK: - 懒加载
    lazy var scrollView = UIScrollView()
    lazy var imageView = UIImageView()
    private lazy var placeHolderImageView: ProgressImageView = ProgressImageView()
}
        
extension PhotoBrowserCell: UIScrollViewDelegate {
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return imageView
    }
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
        //******view 中要用frame.height不能用bounds.height!!!
        var offsetY = (scrollView.bounds.height - view!.frame.height) * 0.5
        offsetY = offsetY < 0 ? 0: offsetY
        
        var offsetX = (scrollView.bounds.width - view!.frame.width) * 0.5
        offsetX = offsetX < 0 ? 0: offsetX
        
        scrollView.contentInset = UIEdgeInsetsMake(offsetY, offsetX, 0, 0)
    }
            
}
